/**
 * 封装ajax请求，开放相关的接口，并实现自动循环调用等功能
 * 
 * @author wjm
 * @build 2015-03-03 
 * TODO 整理实现，与Widget的生命周期相一致
 * @version 0.0.5
 * @bug  fixed 自动循环调用的机制有bug，需要对实现逻辑进行调整
 * 
 * @version 0.1.0
 * @fiexed 2015-03-17 修改自动循环的调用机制中存在的bug
 * 
 * @version 0.1.1 2015-03-07 将事件触发机制抽象到_Monitor类，取消原有的事件触发机制，支持"load","error"两类事件
 */
define([ "base/declare","base/_Monitor", "jquery" ], function(declare,_Monitor, $) {
	var Data = declare([_Monitor], {
		constructor : function(cfg) {
			this.isRunning = false;
			this.cfg = {
				interval : false,
				maxError : 10
			};
			this.errorNum = 0;
			$.extend(this.cfg, cfg);
		},
		setConfig : function(cfg){
			$.extend(true,this.cfg,cfg);
		},
		/**
		 * 
		 * @returns
		 */
		load : function() {
			if (this.isRunning) {
				return this._ajax;
			}
			this.isRunning = true;
			this._ajax = null;
			//关闭原有的自动执行逻辑
			if(this._timeout){
				clearTimeout(this._timeout);
				this._timeout = null;
			}
			var that = this;
			
			var ajax = this._ajax = $.ajax({
				url : this.cfg.url,
				data : this.cfg.params,
				type : this.cfg.type||"post",
				dataType : "json"
			});

			if (this.cfg.interval && this.errorNum < this.cfg.maxError && !this.stopped) {
				ajax.then(function(){
					that._timeout =setTimeout(function(){
						that.load.call(that);
					},that.cfg.interval);
				});
			}
			
			ajax.then(function(data) {
				that.fire("load",data);
				that.isRunning = false;
			}, function(err) {
				that.fire("error",err);
				that.isRunning = false;
				that.errorNum++;
			});
			return ajax;
		},
		/**
		 * 开始数据加载
		 */
		start : function() {
			this._stop();
			this.stopped = false;
			this.fire("start");
			this.load();
		},
		/**
		 * 停止数据加载
		 */
		_stop : function() {
			//关闭原有的自动执行逻辑
			if(this._timeout){
				clearTimeout(this._timeout);
				this._timeout = null;
			}
			if (this._ajax && this.isRunning) {
				this._ajax.abort();
				this.isRunning =false;
			}
			this.errorNum=0;
			this.stopped = true;
		},
		stop : function(){
			this.fire("stop");
			this._stop();
		}
	});
	return Data;
});